import { useEffect, useState } from "react";
import styles from "./Eye.module.scss";
function Eye({ size, r, color, left, top, onClick }) {
	const [eyeBallPos, setEyeBallPos] = useState({ rx: "50%", ry: "50%" });
	useEffect(() => {
		console.log("mount");
		const handleMouseMove = ({ x, y }) => {
			const cx = left + size / 2; //中心x
			const cy = top + size / 2; //中心y
			const l = Math.sqrt((x - cx) ** 2 + (y - cy) ** 2); //鼠标到中心距离
			const maxR = size / 2 - r;
			const sin = (y - cy) / l;
			const cos = (x - cx) / l;
			const rr = l > maxR ? maxR : l; //眼球距离中心的距离
			const rx = rr * cos + size / 2;
			const ry = rr * sin + size / 2;
			console.log(rx, ry);
			setEyeBallPos({ rx, ry });
		};
		window.addEventListener("mousemove", handleMouseMove);
		return () => {
			console.log("unmount");
			window.removeEventListener("mousemove", handleMouseMove);
		};
	}, []);
	const eyeBallStyle = {
		left: eyeBallPos.rx,
		top: eyeBallPos.ry,
	};
	return (
		<div
			className={styles.eye}
			style={{ left, top, width: size, height: size }}
			onClick={onClick}>
			<div
				className={styles.eyeBall}
				style={{
					width: r * 2,
					height: r * 2,
					backgroundColor: color,
					...eyeBallStyle,
				}}></div>
		</div>
	);
}
export default Eye;
